package com.guigu.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.pojo.*;
import com.guigu.service.GatherDetailsService;
import com.guigu.service.GatherService;
import com.guigu.service.ProductService;
import com.guigu.service.PurchaseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 入库单表 前端控制器
 * </p>
 *
 * @author Mr.Zhang
 * @since 2025-03-12
 */
@CrossOrigin
@RestController
@RequestMapping("/gather")
public class GatherController {

    @Autowired
    private GatherService gatherService;

    @Autowired
    private GatherDetailsService gatherDetailsService;

    @Autowired
    private ProductService productService;

    @Autowired
    private PurchaseOrderService purchaseOrderService;
    // 生成订单号（long 类型）
    private static String date;
    private static long orderNum = 0L;

    public static synchronized long getOrderNo() {
        String str = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
        if (date == null || !date.equals(str)) {
            date = str;
            orderNum = 0L;
        }
        orderNum++;
        long orderNO = Long.parseLong(date) * 10000;
        orderNO += orderNum;
        return orderNO;  // 返回 long 类型订单号
    }
    @PostMapping("/gatherReview")
    @ResponseBody
    public Page<Gather> payRevie(@RequestBody HashMap<String, Object> map){
        Page<Gather> payPage = gatherService.gatherReview(map);
        System.out.println(payPage);
        return payPage;
    }

    @PostMapping("/gatherReview2")
    @ResponseBody
    public Page<Gather> payRevie2(@RequestBody HashMap<String, Object> map){
        Page<Gather> payPage = gatherService.gatherReview2(map);
        System.out.println(payPage);
        return payPage;
    }

    @PostMapping("/saveGather")
    @ResponseBody
    public Boolean saveGather(@RequestBody ArrayList<Object> data){
        System.out.println(data);
        // 采购订单id
        Integer purchaseId = 0;
        //入库人
        String storer = "";
        //总件数
        Integer totalAomount = 0;
        //总金额
        Float totalPrice = 0F;
        //登记人
        String register = "";
        //拿到第一个集合
        if (data.get(0) instanceof HashMap) {
            HashMap<String, Object> map = (HashMap<String, Object>) data.get(0);
            if(map.get("purchaseId")!=null){
                purchaseId = Integer.valueOf(Integer.parseInt(map.get("purchaseId").toString()));
            }
            if(map.get("storer")!=null){
                storer = map.get("storer").toString();
            }
            if(map.get("totalAmount")!=null){
                totalAomount = Integer.valueOf(Integer.parseInt(map.get("totalAmount").toString()));
            }
            if(map.get("totalPrice")!=null){
                totalPrice =Float.valueOf(Float.parseFloat(map.get("totalPrice").toString()));
            }
            if(map.get("register")!=null){
                register = map.get("register").toString();
            }
        } else {
            System.out.println("First element is not a HashMap");
            return false;
        }
        //获取入库明细表
        ArrayList<GatherDetails> details = new ArrayList<>();
        ArrayList<HashMap<String, Object>> map1 = (ArrayList<HashMap<String, Object>>) data.get(1);
        for (int i = 0; i < map1.size(); i++) {
            System.out.println(map1);

            HashMap<String, Object> map = (HashMap<String, Object>) map1.get(i);
            GatherDetails gatherDetails = new GatherDetails();
            gatherDetails.setProductId(Integer.valueOf(Integer.parseInt(map.get("productId").toString())));
            gatherDetails.setSupplierId(Integer.valueOf(Integer.parseInt(map.get("supplierId").toString())));
            gatherDetails.setAmount(Integer.valueOf(Integer.parseInt(map.get("count").toString())));
            gatherDetails.setPrice(Float.valueOf(Float.parseFloat(map.get("price").toString())));
            gatherDetails.setSubTotal(Float.valueOf(Float.parseFloat(map.get("subTotal").toString())));
            gatherDetails.setStockId(1);
            gatherDetails.setRealAmount(Float.valueOf(Float.parseFloat(map.get("confirmCount").toString())));

            details.add(gatherDetails);

        }
        long orderNo = getOrderNo();
        Gather gather = new Gather();
        gather.setGatherOrderNumber(String.valueOf(orderNo));
        gather.setStockId(1);
        gather.setStorer(storer);
        gather.setReason("采购入库");
        gather.setTotalAmount(totalAomount);
        gather.setTotalPrice(totalPrice);
        gather.setPurchaseId(purchaseId);
        gather.setRegister(register);
        gather.setRegisterTime(new Date());
        gather.setChecker("");
        gather.setCheckTime(new Date());
        gather.setCheckReason("");

        int id = gatherService.addGather(gather);
        boolean a = false;
        for (GatherDetails gatherDetails :details){
            gatherDetails.setGatherId(id);
            a = gatherDetailsService.save(gatherDetails);
        }
        boolean c = false;
        if (a == true){
            System.out.println("入库成功");
            PurchaseOrder purchaseOrder = purchaseOrderService.getById(purchaseId);
            //修改该采购单的配送状态
            System.out.println(purchaseOrder);
            purchaseOrder.setConveyTag("P001-3");
            c = purchaseOrderService.saveOrUpdate(purchaseOrder);
            System.out.println(purchaseOrder);
        }
        if(c){
            return true;
        }
        return false;
    }

    @PostMapping("/review")
    @ResponseBody
    public Boolean review(@RequestBody HashMap<String, Object> map){
        System.out.println(map);
        String gatherOrderNumber = map.get("gatherOrderNumber").toString();
        System.out.println(gatherOrderNumber);
        Gather gather = gatherService.getGatherBygatherOrderNumber(gatherOrderNumber);
        boolean b = false;
        //拿到入库单id，修改商品库存数量
        Integer gatherId = gather.getGatherId();
        List<GatherDetails> gatherDetails = gatherDetailsService.getGatherDetails2(gatherId);
        for (GatherDetails gatherDetail : gatherDetails) {
            System.out.println(gatherDetail);
            Float realAmount = gatherDetail.getRealAmount();
            System.out.println(realAmount);
            Product product = productService.getById(gatherDetail.getProductId());
            product.setStock((int) (product.getStock() + realAmount));
            b = productService.saveOrUpdate(product);
        }

        gather.setChecker(map.get("reviewer").toString());
        gather.setCheckTime(new Date());
        gather.setCheckReason(map.get("reason").toString());
        gather.setCheckTag("S001-3");
        boolean a = gatherService.saveOrUpdate(gather);

        if(a == true && b == true){
            return true;
        }
        return false;
    }
}

